package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutcoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutcoScanService autcoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1、检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2、根据id查询文章(WmNews)
        WmNews wmNews = this.getById(dto.getId());

        //3、如果查不到返回错误
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4、检查文章的状态是否为已发布（9）
        if(wmNews.getStatus()!=WmNews.Status.PUBLISHED.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"非发布的文章无法上下架");
        }

         //5、修改wnNews的enable的值
         wmNews.setEnable(dto.getEnable().shortValue());
        this.updateById(wmNews);

        //6、将文章的article_id和状态发到kafka里面  {"articleId":"23456789345678",enable:0}
        Map map = new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",dto.getEnable());

        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));

        return ResponseResult.okResult(null);
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto dto) {

        //1、参数校验
        if(dto==null || StringUtils.isBlank(dto.getTitle())  || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser wmUser = WmThreadLocalUtil.get();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        //2、向Wm_news表中添加文章
        //2.1  准备WmNews对象
        WmNews wmNews = new WmNews();
        //2.2将前端的数据拷贝到wmnews对象
        BeanUtils.copyProperties(dto,wmNews);
        //2.3 给作者id赋值
        wmNews.setUserId(wmUser.getId());
        //2.4 给提交、创建时间赋初值
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //2.5 给封面图片的地址赋值
        if(dto.getImages()!=null && dto.getImages().size()>0){
            String image= StringUtils.join(dto.getImages(),",");
            wmNews.setImages(image);
        }
        //2.6 封面类型
        if(dto.getType()==-1){      //说明封面暂时无法确定，需要从内容中提取图片，然后再来绝定
           wmNews.setType(null);
        }
        //2.7 保存或更新文章
        saveOrUpdateNews(wmNews);

        //3、如果是存为草稿则文章发布业务就结束
        if(dto.getStatus()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }


        //4、建立文章与素材之间的关系

        //4.1 建立文章内容图片与文章之间的关联关系
        //4.1.1 抽取内容中所有的图片地址
        List<String> imageList=  extractImageList(wmNews);   //存放的是内容图片的地址
        if(imageList.size()>0){   //如果内容中有图片

            //获取图片的id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));

            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //如果ids的长度和imageList的长度不一致
            if(imageList.size()!=ids.size()){
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
            }

            //建立素材和文章的关联关系
            wmNewsMaterialMapper.saveRelation(ids,wmNews.getId(),(short)0);
        }


        //4.2 建立封面图片和素材的关系
        //4.2.1 处理封面图片自动识别的情况
        if(dto.getType()==-1){

            if(imageList.size()>=3){  //如果内容中的图片超过3张
                wmNews.setType((short)3);
                List<String> collect = imageList.stream().limit(3).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(collect,","));
            }else if(imageList.size()>0){
                wmNews.setType((short)1);
                List<String> collect = imageList.stream().limit(1).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(collect,","));
            }else{
                wmNews.setType((short)0);
            }

            this.updateById(wmNews);
        }

        //4.2.2 获取到封面图片的地址
        String images = wmNews.getImages();
        if(StringUtils.isNotBlank(images)){
            String[] split = images.split(",");   //获取图片的路径
            //获取封面图片的id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl,split ));
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            if(split.length!=ids.size()){
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
            }
            wmNewsMaterialMapper.saveRelation(ids,wmNews.getId(),(short)1);
        }


        //////////////////////////////////文章发布完成/////////////////////////////////////////////////////


        //开始文章审核，审核通过之后需要将文章(wm_news)同步到(ap_article、ap_article_content、ap_article_content)表中
        //autcoScanService.autoScan(wmNews.getId());

        //将保存的文章wmNews封装成一个task对象，然后发给leadnews-schedule微服务
            wmNewsTaskService.saveTask(wmNews);




        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 抽取文章内容中图片的地址
     * @param wmNews
     * @return
     */
    private List<String> extractImageList(WmNews wmNews) {
        String content = wmNews.getContent();
        List<String> imageUrlList = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if("image".equals(map.get("type"))){
                imageUrlList.add(map.get("value").toString());
            }
        }
        return imageUrlList;
    }

    /**
     * 保存或更新文章
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {

        if(wmNews.getId()==null){
            //说明需要保存文章
            this.save(wmNews);
        }else{
            //更新文章、删除文章与素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //更新文章
            this.updateById(wmNews);
        }

    }







    /**
     * 带条件的文章查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {

        //1、参数检测
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2、判断用户
        WmUser wmUser = WmThreadLocalUtil.get();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3、准 备分页条件
        IPage page = new Page(dto.getPage(),dto.getSize());

        //4、准 备查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //4.1 设置当前用户
        lambdaQueryWrapper.eq(WmNews::getUserId,wmUser.getId());
        //4.2 关键字
        if(StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword()) ;
        }
        //4.3 频道
        if(dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId()) ;
        }
        //4.4 文章状态
        if(dto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //4.5  发布时间
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //4.6 按照创建时间进行排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //5、查询
        page(page,lambdaQueryWrapper);

        //6、封装结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());

        return result;
    }
}
